package com.gxuwz.com_property.login.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.gxuwz.com_property.utils.RedisUtil;
import com.gxuwz.com_property.utils.UUIdUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;
@RestController
public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisUtil redisUtil;


    @GetMapping("/captcha.jpg")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置响应类型
        response.setContentType("image/jpeg");
        // 不缓存内容
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setDateHeader("Expires", 0);
        // 生成验证码字符串
        String text = defaultKaptcha.createText();
        System.out.println("test:"+text);
        // 将验证码值存储到 Redis 中

        /*String key = "captcha:" + UUIdUtils.simpleUUID();*/
        String key = "captcha:" + text;
        System.out.println("key:"+key+":test:"+text);
        redisUtil.set(key, text, 60, TimeUnit.SECONDS);

        // 创建验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        // 输出图片到客户端

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

}
